package com.quantdo.apex.elasticjob.util;

import com.quantdo.apex.elasticjob.model.Response;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.ConnectException;

/**
 * @author chenkuan
 * @version v1.0
 * @desc Http请求工具类
 * @date 2019/12/12 012 9:43
 */
public class HttpClientUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	/**
	 * Post方法
	 *
	 * @param url       请求url
	 * @param paramJson 请求参数json
	 */
	public static Response<String> sendPost(String url, String paramJson) {
		try {
			HttpClient httpClient = new HttpClient();
			httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
			PostMethod postMethod = new PostMethod(url);
			postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
			postMethod.addRequestHeader("Content-Type", "application/json; charset=UTF-8");
			if (StringUtils.isNotEmpty(paramJson)) {
				RequestEntity entity = new StringRequestEntity(paramJson, "application/json", "UTF-8");
				postMethod.setRequestEntity(entity);
			}
			httpClient.executeMethod(postMethod);
			InputStream inputStream = postMethod.getResponseBodyAsStream();
			String result = IOUtils.toString(inputStream, "UTF-8");
			postMethod.releaseConnection();
			logger.debug("Post Request:{} Return:{}", url, result);
			return new Response<String>().result(result);
		} catch (ConnectException e) {
			logger.warn("远程服务:{} 异常,连接失败", url);
		} catch (Exception e) {
			logger.error("Post方法,远程调用时出错", e);
		}
		return Response.fail("Post方法,远程调用时出错");
	}

	/**
	 * Get方法
	 *
	 * @param urlParam url请求，包含参数
	 */
	public static Response<String> sendGet(String urlParam) {
		try {
			HttpClient httpClient = new HttpClient();
			httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
			GetMethod getMethod = new GetMethod(urlParam);
			getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
			getMethod.addRequestHeader("Content-Type", "application/json; charset=UTF-8");
			httpClient.executeMethod(getMethod);
			InputStream inputStream = getMethod.getResponseBodyAsStream();
			String result = IOUtils.toString(inputStream, "UTF-8");
			getMethod.releaseConnection();
			logger.debug("Get Request:{} Return:{}", urlParam, result);
			return new Response<String>().result(result);
		} catch (ConnectException e) {
			logger.warn("远程服务:{} 异常,连接失败", urlParam);
		} catch (Exception e) {
			logger.error("Get方法,远程调用时出错", e);
		}
		return Response.fail("Get方法,远程调用时出错");
	}
}
